package edu.nju.desserthouse.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import nju.edu.desserthouse.model.Bonus;
import edu.nju.desserthouse.dao.BonusDao;

/**
 * Session Bean implementation class BonusDao
 */
@Stateless
public class BonusDaoBean implements BonusDao{
	
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName = "desserthouseJPA")
	protected EntityManager em;
	
	public BonusDaoBean(){
		
	}
	
	@Override
	public boolean save(Bonus bonus) {
		try{
			em.persist(bonus);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Bonus find(String column, String value) {
		Bonus bonus = null;
		try{
			Query query = em.createQuery("from Bonus b where b." + column + "=" + value);
			bonus = (Bonus)query.getSingleResult();
			em.clear();
			return bonus;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean UpdateByBonusId(Bonus bonus) {
		try{
			em.merge(bonus);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	@Override
	public ArrayList<Bonus> getBonusList() {
		try{
			Query query = em.createQuery("from Bonus b where b.id > 0");
			@SuppressWarnings("unchecked")
			List<Bonus> bonus = query.getResultList();
			if(bonus != null){
				ArrayList<Bonus> bonusList = new ArrayList<Bonus>(bonus);
				em.clear();
				return bonusList;
			}else{
				System.out.println("NULL RESULT!!!");
				em.clear();
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
}
